﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;

[assembly:TagPrefix("AspJqGrid","AllenJqGrid")]
namespace AspJqGrid
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:JqGrid runat=server></{0}:JqGrid>")]
    public class JqGrid : WebControl
    {
        #region 表体参数
        //每页显示行数默认50
        private int _rowNum = 50;
        [Description("每页显示行数")]
        public int RowNum
        {
            get { return _rowNum; }
            set { _rowNum = value; }
        }

        //排序字段默认id
        private string _sortname = "id";
        [Description("排序字段")]
        public string Sortname
        {
            get { return _sortname; }
            set { _sortname = value; }
        }

        //排序顺序
        private string _sortorder = "desc";
        [Description("排序字段")]
        public string Sortorder
        {
            get { return _sortorder; }
            set { _sortorder = value; }
        }

        //是否显示总数量，默认是
        private bool _viewrecords = true;
        [Description("显示总数量")]
        public bool Viewrecords
        {
            get { return _viewrecords; }
            set { _viewrecords = value; }
        }

        //是否使用滚动条翻页，默认否
        private bool _scroll = false;
        [Description("是否使用滚动条翻页")]
        public bool Scroll
        {
            get { return _scroll; }
            set { _scroll = value; }
        }

        //每页显示行数选择
        private string _rowList="[10,20,50]";
         [Description("每页显示行数选择，格式：[10,20,50]")]
        public string RowList
        {
            get { return _rowList; }
            set { _rowList = value; }
        }

        //是否显示行号，默认是
        private bool _rownumbers = true;
        [Description("是否显示行号")]
        public bool Rownumbers
        {
            get { return _rownumbers; }
            set { _rownumbers = value; }
        }

        //行号宽度默认30
        private int _rownumWidth = 30;
        [Description("行号宽度")]
        public int RownumWidth
        {
            get { return _rownumWidth; }
            set { _rownumWidth = value; }
        }

        //表格高度默认400
        private int _height = 400;
        [Description("表格高度")]
        public int GridHeight
        {
            get { return _height; }
            set { _height = value; }
        }

        //表格名称
        private string _caption = string.Empty;
        [Description("表格名称，如果为空则不显示表格名称行")]
        public string Caption
        {
            get { return _caption; }
            set { _caption = value; }
        }
        //多选，默认否
        private bool _multiselect = false;
        [Description("多选，默认否")]
        public bool Multiselect
        {
            get { return _multiselect; }
            set { _multiselect = value; }
        }
        #endregion

        #region 动作按钮
        private string _dblClickRowFnName = string.Empty;
        private bool _search = false;
        private bool _add = false;
        private bool _edit = false;
        private bool _del = false;
        [Description("是否支持行双击事件，需要客户端自行构造双击事件方法，默认否")]
        public string DblClickRowFnName
        {
            get { return _dblClickRowFnName; }
            set { _dblClickRowFnName = value; }
        }
        [Description("是否可查询，默认否")]
        public bool Search
        {
            get { return _search; }
            set { _search = value; }
        }
        [Description("是否可添加，默认否")]
        public bool Add
        {
            get { return _add; }
            set { _add = value; }
        }
        [Description("是否可编辑，默认否")]
        public bool Edit
        {
            get { return _edit; }
            set { _edit = value; }
        }
        [Description("是否可删除，默认否")]
        public bool Del
        {
            get { return _del; }
            set { _del = value; }
        }
        #endregion

        #region 数据库相关
        //字段名称
        private string _fields = "*";
        [Description("字段名称，格式如：id,field1,field2")]
        public string Fields
        {
            get { return _fields; }
            set { _fields = value; }
        }

        //表名
        private string _tableName;
        [Description("表名")]
        public string TableName
        {
            get { return _tableName; }
            set { _tableName = value; }
        }
        #endregion

        protected override void OnPreRender(EventArgs e)
        {
            this.Page.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
            base.OnPreRender(e);
        }

        //向页面注册css和js
        void Page_PreRenderComplete(object sender, EventArgs e)
        {
            HtmlLink jqGridStyle = new HtmlLink();
            jqGridStyle.Attributes["type"] = "text/css";
            jqGridStyle.Attributes["rel"] = "stylesheet";
            jqGridStyle.Attributes["href"] = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "AspJqGrid.Css.ui.jqgrid.css");
            this.Page.Header.Controls.Add(jqGridStyle);

            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "AspJqGrid.Scripts.grid.locale-cn.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "AspJqGrid.Scripts.jquery.jqGrid.min.js");
        }

        //构造jqGrid页面JS，主体功能
        private string BuildJqGridHtml()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\n<script type=\"text/javascript\">\n");
            sb.Append("$(function(){\n");
            //-----------------------------------------------jqGrid js构造开始
            sb.Append("$(\"#" + this.ID + "Table\").jqGrid({\n");
            sb.Append("url:\"data.ashx?tablename=" + TableName + "&action=view\",\n");
            sb.Append("datatype: 'json',\n");   //此处原为dataType，则无法处理数据状态，大小写敏感
            sb.Append("rowNum: " + RowNum + ",\n");
            sb.Append("pager: '#" + this.ID + "Pager',\n");
            sb.Append("sortname: '" + Sortname + "',\n");
            sb.Append("sortorder: '" + Sortorder + "',\n");
            sb.Append("viewrecords: true,\n");
            if (Scroll) sb.Append("scroll: 1,\n"); else sb.Append("rowList:" + RowList + ",\n");
            if (Rownumbers) { sb.Append("rownumbers: true,\n"); sb.Append("rownumWidth: " + RownumWidth + ",\n"); }
            sb.Append("height: "+GridHeight+",\n");
            if (Caption != string.Empty) sb.Append("caption:'" + Caption + "',\n");
            if (Multiselect) sb.Append("multiselect: " + Multiselect + ",\n");
            if (Edit) sb.Append("editurl:'data.ashx?tablename=" + TableName + "&action=edit',\n");
            if (DblClickRowFnName!=string.Empty) sb.Append("ondblClickRow:" + DblClickRowFnName + ",\n");

            #region colModel构造开始，由配置文件完成
            sb.Append("colModel:[\n");
            string xmlPath = System.AppDomain.CurrentDomain.BaseDirectory + "config/" + TableName + ".xml";
            if (System.IO.File.Exists(xmlPath))
            {
                sb.Append(BuildColModel(xmlPath));
            }
            else
            {
                //如果没有配置文件，则自动初始化生成XML文件
                new jqGridColumnsConfig().BuildColModelXML(xmlPath, Fields, TableName, Edit); 
                sb.Append(BuildColModel(xmlPath));
            }
            sb.Append("],\n");
            #endregion

            sb.Append("gridview:true\n");
            sb.Append("});\n");
            //底部按钮自定义
            //$(\"#" + this.ID + "Table\").jqGrid('navGrid', '#" + this.ID + "Pager', { search: false, add: false, edit: false, del: false, refresh: true });
            sb.Append("$(\"#" + this.ID + "Table\").jqGrid('navGrid','#" + this.ID + "Pager',{");            
            sb.Append("search:false,");
            sb.Append("add:" + Add.ToString().ToLower() + ",addtext:'添加',");
            sb.Append("edit:" + Edit.ToString().ToLower() + ",edittext:'编辑',");
            sb.Append("del:" + Del.ToString().ToLower() + ",deltext:'删除',");
            sb.Append("refresh: true,refreshtext:'重置',");
            sb.Remove(sb.Length - 1, 1);
            sb.Append("});\n");
            if (Search)
            {
                sb.Append("$(\"#" + this.ID + "Table\").jqGrid('navButtonAdd','#" + this.ID + "Pager',{caption: '查询',title: '数据查询',");
                sb.Append("onClickButton : function (){");
                sb.Append("var filterSettings = {");
                sb.Append("multipleSearch:true,");
                sb.Append("closeAfterSearch:true,");
                sb.Append("closeOnEscape:true,");
                sb.Append("loadDefaults:true,");
                sb.Append("sopt: ['cn','ge','le']");
                sb.Append("};");
                sb.Append("$(\"#" + this.ID + "Table\").jqGrid('searchGrid', filterSettings);");
                sb.Append("}\n});\n");
            }
            //-----------------------------------------------jqGrid js构造结束
            sb.Append("});\n");
            sb.Append("</script>");
            return sb.ToString();
        }

        protected string BuildColModel(string xmlPath)
        {
            StringBuilder sb = new StringBuilder();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            XmlNodeList xnList = xmlDoc.SelectNodes("root//columns");
            foreach (XmlNode xn in xnList)
            {
                if (xn.Attributes["IsIdentity"] == null || xn.Attributes["IsIdentity"].Value == "False")
                {
                    sb.Append("{");
                    for (int i = 0; i < xn.Attributes.Count; i++)
                    {
                        switch (xn.Attributes.Item(i).Name)
                        {
                            case "editrules":
                            case "editable":
                                sb.Append(xn.Attributes.Item(i).Name + ":" + xn.Attributes.Item(i).Value + ",");
                                break;
                            default:
                                sb.Append(xn.Attributes.Item(i).Name + ":'" + xn.Attributes.Item(i).Value + "',");
                                break;
                        }
                    }
                    sb.Remove(sb.ToString().Length - 1, 1);
                    sb.Append("},");
                }
            }
            sb.Remove(sb.ToString().Length - 1, 1);
            sb.Append("\n");
            return sb.ToString();
        }

        //输出表格框架
        protected override void RenderContents(HtmlTextWriter output)
        {
            string jqGridTag = "\n<table id=\"" + this.ID + "Table\"></table>\n<div id=\"" + this.ID + "Pager\"></div>";
            output.Write(BuildJqGridHtml() + jqGridTag);
        }
    }
}
